// import 'dart:typed_data';
// import 'dart:ui';

// import 'package:flutter/material.dart';
// import 'package:flutter/rendering.dart';
// import 'package:flutter/services.dart';
// import 'package:flutter_screenutil/flutter_screenutil.dart';
// import 'package:image_gallery_saver/image_gallery_saver.dart';
// import 'package:pipeline_flutter/common_widget/appbar_widget.dart';
// import 'package:pipeline_flutter/tools/const_config.dart';
// import 'package:pipeline_flutter/tools/select_file_util.dart';

// class SignNamePage extends StatefulWidget {
//   @override
//   _SignNamePageState createState() => _SignNamePageState();
// }

// class _SignNamePageState extends State<SignNamePage> {
//   GlobalKey key = GlobalKey();
//   PointerEvent? _event;
//   List<Offset?> _points = <Offset>[];
//   Color selectColor = Colors.red;
//   Uint8List? _postBytes;
//   @override
//   void initState() {
//     super.initState();
//   }

//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       body: Column(children: [
//         Container(
//           color: TKConstantConfig.MAINCOLOR,
//           child: CommonAppBar("签名", () {
//             Navigator.pop(context);
//           }, rightWidget: _rightNavWidget()),
//         ),
//         RepaintBoundary(
//           key: key,
//           child: Stack(children: [
//             Listener(
//               child: Container(
//                 alignment: Alignment.center,
//                 color: Colors.white,
//                 width: ScreenUtil().screenWidth,
//                 height: ScreenUtil().screenWidth,
//                 // child: Text(_event?.toString() ?? "",
//                 //     style: TextStyle(color: Colors.black)),
//               ),
//               onPointerDown: (PointerDownEvent event) {
//                 setState(() {
//                   _event = event;
//                   _points.add(_event?.localPosition ?? Offset.zero);
//                 });
//               },
//               onPointerMove: (PointerMoveEvent event) {
//                 setState(() {
//                   _event = event;
//                   _points.add(_event?.localPosition ?? Offset.zero);
//                 });
//               },
//               onPointerUp: (PointerUpEvent event) {
//                 setState(() {
//                   _event = event;
//                   _points.add(Offset.zero);
//                 });
//               },
//             ),
//             Positioned(
//                 left: (_event != null ? _event?.position.dx : 0),
//                 top: (_event != null
//                     ? (_event?.position.dy ?? 0) -
//                         TKConstantConfig.appbarHeight -
//                         50
//                     : 0),
//                 child: Container(
//                   width: 1,
//                   height: 1,
//                   color: Colors.black,
//                 )),
//             CustomPaint(painter: new SignaturePainter(_points))
//           ]),
//         ),
//         SizedBox(height: 20),
//         GestureDetector(
//             onTap: () {
//               setState(() {
//                 _points = [];
//               });
//             },
//             child: Container(
//               height: 30,
//               child: Text(
//                 "清空重写",
//                 style: TextStyle(fontSize: 15.sp),
//               ),
//             )),
//       ]),
//     );
//   }

//   Widget _rightNavWidget() {
//     return GestureDetector(
//       onTap: () {
//         _saveSignPic();
//       },
//       child: Container(
//           padding: EdgeInsets.only(right: 15.w),
//           child: Text(
//             "保存",
//             style: TextStyle(
//                 color: Color(0xFFFFFFFF),
//                 fontSize: 16.sp,
//                 fontWeight: FontWeight.normal),
//           )),
//     );
//   }

// ///截图保存至相册并上传至服务器, 拿到图片网络地址,退出页面
//   _saveSignPic() async {
//     RenderRepaintBoundary boundary =
//         key.currentContext!.findRenderObject() as RenderRepaintBoundary;
//     var image = await boundary.toImage(pixelRatio: 3.0);
//     ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
//     _postBytes = byteData?.buffer.asUint8List();
//     //保存到相册
//     var result = await ImageGallerySaver.saveImage(_postBytes!);
//     String path = result['filePath'].replaceAll("file://", '');
//     if (result != null && result != "") {
//     //上传到服务器
//       SelectFileUtil.uploadFile(
//           path, "sign_${DateTime.now().microsecondsSinceEpoch}.png",
//           successCallback: (url) {
//      //拿到服务器返回图片地址,退出页面
//         if (url != null && url.isNotEmpty) {
//           if (!mounted) return;
//           Navigator.of(context).pop(url);
//         }
//       });
//     }
//   }
// }

// class SignaturePainter extends CustomPainter {
//   SignaturePainter(this.points);

//   final List<Offset?> points;
//   final Color paintColor = Colors.black;

//   Paint myPaint = new Paint();

//   void paint(Canvas canvas, Size size) {
//     myPaint.strokeCap = StrokeCap.round;
//     myPaint.strokeWidth = 5.0;
//     for (int i = 0; i < points.length - 1; i++) {
//       if (points[i] != null &&
//           points[i + 1] != null &&
//           points[i] != Offset.zero &&
//           points[i + 1] != Offset.zero) {
//         canvas.drawLine(points[i]!, points[i + 1]!, myPaint);
//       }
//     }
//   }

//   bool shouldRepaint(SignaturePainter other) => other.points != points;
// }
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:magic_car/jiance/pre_test_report.dart';
import 'package:magic_car/user/userPrivate.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:magic_car/main.dart';
import 'package:package_info/package_info.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';

import 'package:signature/signature.dart';
class SignPage extends StatefulWidget {
  SignPage({Key key, this.title}) : super(key: key);

  final String title;
 

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<SignPage> {
  Image images ;
  File tempFile ;
  final SignatureController _controller = SignatureController(
    penStrokeWidth: 1,
    penColor: Colors.red,
    exportBackgroundColor: Colors.blue,
    onDrawStart: () => print('onDrawStart called!'),
    onDrawEnd: () => print('onDrawEnd called!'),
  );

  @override
  void initState() {
    super.initState();
    _controller.addListener(() => print('Value changed'));
  }

    //上传签名图片
  uploadsignpic()async{
    final Uint8List data =
    await _controller.toPngBytes();
    var result ;
         

     if (Platform.isAndroid) {
      if (await Permission.storage.request().isGranted) {
       result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(data)
        );  
      }
    
    } else {
      if (await Permission.photos.request().isGranted) {
      result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(data)
        );  
      }
    }
   // ui.Image img = _controller.toImage();
  
  //  Future<Image> temp= await _controller.toImage().path;
    // File _files = await FlutterNativeImage.compressImage(_imageLocalPath);
  
 
  //   final result = await ImageGallerySaver.saveImage(
  //           data
  //       );  
  //  File saveFile = new File(result.replaceAll("file://", ""));    
  String res1 = result["filePath"]    ;                    
    String res =  res1.replaceAll("file://", '');                 
     Map<String, String> map = new Map();

    HttpHelper.upLoadSignImage(res, (data) {
      //loadpage.close();
      print(data);
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
       
      
      }
    }, params: map);
   }


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Builder(
        builder: (BuildContext context) => Scaffold(
          body: ListView(
            children: <Widget>[
              Container(
                height: 300,
                child: const Center(
                  child: Text('Big container to test scrolling issues'),
                ),
              ),
              //SIGNATURE CANVAS
              Signature(
                controller: _controller,
                height: 300,
                backgroundColor: Colors.lightBlueAccent,
              ),
              //OK AND CLEAR BUTTONS
              Container(
                decoration: const BoxDecoration(color: Colors.black),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  mainAxisSize: MainAxisSize.max,
                  children: <Widget>[
                    //SHOW EXPORTED IMAGE IN NEW ROUTE
                    IconButton(
                      icon: const Icon(Icons.check),
                      color: Colors.blue,
                      onPressed: () async {
                        if (_controller.isNotEmpty) {
                          final Uint8List data =
                              await _controller.toPngBytes();
                              uploadsignpic();
                          // if (data != null) {
                          //   await Navigator.of(context).push(
                          //     MaterialPageRoute<void>(
                          //       builder: (BuildContext context) {
                          //         return Scaffold(
                          //           appBar: AppBar(),
                          //           body: Center(
                          //             child: Container(
                          //               color: Colors.grey[300],
                          //               child: Image.memory(data),
                          //             ),
                          //           ),
                          //         );
                          //       },
                          //     ),
                          //   );
                          // }
                        }
                      },
                    ),
                    //CLEAR CANVAS
                    IconButton(
                      icon: const Icon(Icons.clear),
                      color: Colors.blue,
                      onPressed: () {
                        setState(() => _controller.clear());
                      },
                    ),
                  ],
                ),
              ),
              Container(
                height: 300,
                child: const Center(
                  child: Text('Big container to test scrolling issues'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}